﻿using log4net;
using Newtonsoft.Json;
using SqlSugar;
using System.Configuration;
using System.Linq;
using System.Text;

namespace NCP.Core.DataUtil
{
    public class DbHelper
    {/// <summary>
     /// 获取数据库连接字符串
     /// </summary>
        public static string ConnectionString = ConfigurationManager.ConnectionStrings["default"].ConnectionString;
        private static string isLog = ConfigurationManager.AppSettings["IsLog"];
        private static ILog logger = LogManager.GetLogger(typeof(DbHelper));
        /// <summary>
        /// 获取SqlSugar实例化对象
        /// </summary>
        /// <returns></returns>
        public static SqlSugarClient GetSqlSugarClient()
        {
            ConnectionConfig conn = new ConnectionConfig();
            ICacheService myCache = new HttpRuntimeCache();//缓存
            conn.ConnectionString = ConnectionString;
            conn.DbType = DbType.SqlServer;
            conn.IsAutoCloseConnection = true;
            conn.ConfigureExternalServices = new ConfigureExternalServices()
            {
                DataInfoCacheService = myCache
            };

            SqlSugarClient db = new SqlSugarClient(conn); //默认SystemTable

            db.Aop.OnLogExecuting = (sql, pars) => //SQL执行前事件
            {

            };
            db.Aop.OnLogExecuted = (sql, pars) => {
                logger.Error("执行后sql语句：" + LookSQL(sql, pars));
            };
            db.Aop.OnError = (exp) =>//执行SQL 错误事件
            {
                //exp.sql exp.parameters 可以拿到参数和错误Sql  
                StringBuilder sb_SugarParameterStr = new StringBuilder("###SugarParameter参数为:");
                var parametres = exp.Parametres as SugarParameter[];
                if (parametres != null)
                {
                    sb_SugarParameterStr.Append(JsonConvert.SerializeObject(parametres));
                }

                StringBuilder sb_error = new StringBuilder();
                sb_error.AppendLine("SqlSugarClient执行sql异常信息:" + exp.Message);
                sb_error.AppendLine("###赋值后sql:" + LookSQL(exp.Sql, parametres));
                sb_error.AppendLine("###带参数的sql:" + exp.Sql);
                sb_error.AppendLine("###参数信息:" + sb_SugarParameterStr.ToString());
            };

            return db;
        }

        /// <summary>
        /// 查看赋值后的sql
        /// </summary>
        /// <param name="sql"></param>
        /// <param name="pars">参数</param>
        /// <returns></returns>
        private static string LookSQL(string sql, SugarParameter[] pars)
        {
            if (pars == null || pars.Length == 0) return sql;

            StringBuilder sb_sql = new StringBuilder(sql);
            var tempOrderPars = pars.Where(p => p.Value != null).OrderByDescending(p => p.ParameterName.Length).ToList();//防止 @par1错误替换@par12
            for (var index = 0; index < tempOrderPars.Count; index++)
            {
                sb_sql.Replace(tempOrderPars[index].ParameterName, "'" + tempOrderPars[index].Value.ToString() + "'");
            }

            return sb_sql.ToString();
        }
    }
}
